package com.das.mechanic_base.mvp.view.camera;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.camera.X3CameraPreviewAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.BaseViewProxy;
import com.das.mechanic_base.base.X3BaseFragment;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.CameraCropBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.camera.CameraCloseBean;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3CameraPrograssView;
import com.das.mechanic_base.widget.X3CameraTakeView;
import com.das.mechanic_base.widget.X3PointDialog;
import com.das.mechanic_base.widget.X3ShowImageDialog;
import com.kproduce.roundcorners.RoundImageView;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class X3CameraTakeFragment extends X3BaseFragment implements X3CameraTakeView.IOnClickTake, X3CameraPrograssView.IOnShowTime, X3CameraPreviewAdapter.IOnCameraPreview {

    @BindView(R2.id.cv_view)
    CameraView cv_view;
    @BindView(R2.id.cv_take)
    X3CameraTakeView cv_take;
    @BindView(R2.id.iv_flash)
    ImageView iv_flash;
    @BindView(R2.id.cv_prograss)
    X3CameraPrograssView cv_prograss;
    @BindView(R2.id.tv_min)
    TextView tv_min;
    @BindView(R2.id.tv_finish)
    TextView tv_finish;
    @BindView(R2.id.rl_bottom)
    RelativeLayout rl_bottom;
    @BindView(R2.id.rl_img)
    RelativeLayout rl_img;
    @BindView(R2.id.iv_back)
    ImageView iv_back;
    @BindView(R2.id.iv_last)
    ImageView iv_last;
    @BindView(R2.id.iv_image)
    ImageView iv_image;
    @BindView(R2.id.rlv_camera)
    RecyclerView rlv_camera;
    @BindView(R2.id.iv_camera_notice)
    RoundImageView iv_camera_notice;
    @BindView(R2.id.rl_ai)
    RelativeLayout rl_ai;
    @BindView(R2.id.tv_text)
    TextView tv_text;
    @BindView(R2.id.sb_bar)
    SeekBar sb_bar;
    @BindView(R2.id.iv_ai)
    ImageView iv_ai;

    private String videoSavePath;

    private List<Float> timeList = new ArrayList<>();

    /**
     * 存储多段视频
     */
    private List<String> videoList = new ArrayList<>();

    private float takeTime;

    private X3PointDialog delDialog;

    private X3PointDialog exitDialog;
    private boolean isSuccess;

    private List<String> cameraList;
    private X3CameraPreviewAdapter previewAdapter;
    private String currentPath;
    private Mode mode;
    private int allNum;
    private BaseViewProxy viewProxy;
    private X3ShowImageDialog imageDialog;
    private boolean isTake;

    private int imgHeight;
    private String imgUrl;
    private int isAlbum;
    private long itemId;
    private boolean isWork;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_camera_take_fragment;
    }

    @Override
    protected void initView(View view) {
        Log.e("SSSS","initView：" + System.currentTimeMillis());
        initCamera();

        viewProxy = new BaseViewProxy(getActivity());

        // 实现拍照或者视频的方法
        cv_take.setiOnClickTake(this);
        // 显示拍摄视频的时间
        cv_prograss.setiOnShowTime(this);

        isAlbum = getActivity().getIntent().getIntExtra("isAlbum", 0);
        //3故障灯 4外观损伤
      //  rl_ai.setVisibility((isAlbum == 3 || isAlbum == 4) ? View.VISIBLE : View.GONE);
        if(isAlbum == 3){
            rl_ai.setVisibility(View.VISIBLE);
            tv_text.setText( getString(R.string.x3_camera_ai_text_notice_light));

        }else if(isAlbum == 4){
            rl_ai.setVisibility(View.VISIBLE);
            tv_text.setText( getString(R.string.x3_camera_ai_text_notice));
        }else {
            rl_ai.setVisibility(View.GONE);
        }


        allNum = getActivity().getIntent().getIntExtra("allNum", 9);

        imgUrl = getActivity().getIntent().getStringExtra("imgUrl");

        itemId = getActivity().getIntent().getLongExtra("itemId", 0L);

        isWork = getActivity().getIntent().getBooleanExtra("isWork", false);

        iv_camera_notice.setVisibility(X3StringUtils.isEmpty(imgUrl) ? View.GONE : View.VISIBLE);

        Glide.with(getContext()).load(X3StringUtils.getImageUrl(imgUrl)).into(iv_camera_notice);

        cameraList = new ArrayList<>();

//        rlv_camera.setVisibility((allNum == 1 && (isAlbum == 4 || isAlbum == 3)) ? View.GONE : View.VISIBLE);

        rlv_camera.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false));

        previewAdapter = new X3CameraPreviewAdapter(getActivity());

        rlv_camera.setAdapter(previewAdapter);

        previewAdapter.setiOnCameraPreview(this);

        iv_image.post(() -> imgHeight = iv_image.getHeight());

        sb_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                cv_view.setZoom(progress * 0.01f);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        rectParams();
    }

    private void rectParams(){
        if (X3ScreenUtils.getScreenWidth(getActivity()) == 1080 && X3ScreenUtils.getScreenHeight(getActivity()) == 1920) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) iv_ai.getLayoutParams();
            layoutParams.height =  X3ScreenUtils.dip2px(180,getActivity());
            layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            iv_ai.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        /**
         * 这里不用cv.istakeVideo判断 是否在拍摄视频 是因为onStop获取不到cv_view的状态
         */
        if (cv_prograss != null && cv_prograss.getValueAnimator() != null && cv_prograss.getValueAnimator().isRunning()) {
            cv_prograss.stopVideo();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }

    private void initCamera() {
        cv_view.setLifecycleOwner(getViewLifecycleOwner());
        cv_view.open();
        int v = (int) (cv_view.getZoom() * 100);
        sb_bar.setProgress(v);

        cv_view.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                super.onPictureTaken(result);

                File imgFile = new File(X3FileUtils.getStoragePath(getActivity(), X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg");
                if (!imgFile.getParentFile().exists()) {
                    imgFile.getParentFile().mkdirs();
                }
                if (!imgFile.exists()) {
                    try {
                        imgFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                result.toFile(imgFile, file2 -> {
                    Log.e("up_load_","file2.getPath() =" + file2.getPath());
                    cameraList.add(file2.getPath());
                    if (mode == Mode.VIDEO) {
                        return;
                    }
                    isTake = false;
                    tv_finish.setVisibility(View.VISIBLE);
                    tv_finish.setText(cameraList.size() +"/" + allNum + "\n" + getString(R.string.x3_camera_crop_ok));
                    if (previewAdapter != null) {
                        previewAdapter.changeCameraList(cameraList,mode);
                        // 滑动指定位置
                        rlv_camera.smoothScrollToPosition(previewAdapter.getItemCount() - 1);
                    }
                });
            }

            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                super.onCameraOpened(options);
                Log.e("SSSS","onCameraOpened：" + System.currentTimeMillis());
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                super.onVideoTaken(result);
                String path = result.getFile().getPath();
                ((X3CameraPhotoActivity)getActivity()).hideOrShowTabottom(true);
                videoList.add(path);
                if (mode == Mode.PICTURE) {
                    return;
                }
                tv_finish.setVisibility(View.VISIBLE);
                tv_finish.setText(getString(R.string.x3_camera_crop_ok));
                if (previewAdapter != null) {
                    previewAdapter.changeCameraList(videoList,mode);
                    rlv_camera.smoothScrollToPosition(previewAdapter.getItemCount() - 1);
                }
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
                super.onCameraError(exception);
                Log.e("SSSS","相机错误:" + exception.toString() + "::"+ exception.getReason());
            }
        });
    }

    /**
     * 是否从拍照模式转换为预览模式
     * @param isPreview
     * @param path
     */
    protected void isPreviewCamera(boolean isPreview,Object path) {
        if (isPreview && path == null) {
            return;
        }
        if (path != null) {
            X3GlideNewUtils.loadNormalImage(getActivity(), path,iv_image, Color.BLACK);
        }
        // 先隐藏底部导航和返回键
        iv_back.setVisibility(isPreview ? View.GONE : View.VISIBLE);
        //rl_bottom.setVisibility(isPreview ? View.GONE : View.VISIBLE);
        rl_img.setVisibility(isPreview ? View.VISIBLE : View.GONE);
        cv_view.setVisibility(isPreview ? View.GONE : View.VISIBLE);
        if (!"off".equals(iv_flash.getTag())) {
            iv_flash.performClick();
        }

        if (isPreview) {
            rl_ai.setVisibility(View.GONE);
        }else {
            if (isAlbum == 3 || isAlbum ==4) {
                rl_ai.setVisibility(View.VISIBLE);
            }else {
                rl_ai.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 展示拍摄视频或者拍照
     * @param currentIndex
     */
    public void showVideoOrPicture(int currentIndex) {
        this.mode = (currentIndex == 1) ? Mode.VIDEO : Mode.PICTURE;
        if (getActivity() == null) {
            return;
        }
        if (getActivity().isFinishing()) {
            return;
        }
        rl_img.setVisibility(View.GONE);
        this.currentPath = "";
        iv_flash.setTag("off");
        iv_flash.setVisibility(currentIndex == 1 ? View.GONE : View.VISIBLE);

        cv_view.post(() -> {
            Mode cameraMode = cv_view.getMode();
            if (cameraMode == Mode.PICTURE && currentIndex == 1) {
                cv_view.setMode(Mode.VIDEO);
            }else if (cameraMode == Mode.VIDEO && currentIndex != 1) {
                cv_view.setMode(Mode.PICTURE);
            }
        });

        cv_take.setVisibility(View.VISIBLE);
        // 重置下页面 不然会黑屏 因为预览imageview没有被隐藏
        isPreviewCamera(false,null);
        tv_min.setVisibility(View.INVISIBLE);
        if (previewAdapter != null) {
            switch (currentIndex) {
                case 1:
                    // 视频
                    previewAdapter.changeCameraList(videoList,mode);
                    tv_min.setVisibility(!X3StringUtils.isListEmpty(videoList) ? View.VISIBLE : View.INVISIBLE);
                    tv_finish.setVisibility(!X3StringUtils.isListEmpty(videoList) ? View.VISIBLE : View.GONE);
                    tv_finish.setText(getString(R.string.x3_camera_crop_ok));
                    break;
                default:
                    // 图片
                    tv_finish.setVisibility(!X3StringUtils.isListEmpty(cameraList) ? View.VISIBLE : View.GONE);
                    tv_finish.setText(cameraList.size() +"/" + allNum + "\n"+getString(R.string.x3_camera_crop_ok));
                    previewAdapter.changeCameraList(cameraList,mode);
                    break;
            }
        }

        resetPrograss();
        cv_take.post(() -> {
            if (currentIndex == 1) {
                cv_take.pictureToVideo();
            }else {
                cv_take.videoToPicture();
            }
        });
    }

    private void resetPrograss() {
        cv_prograss.setVisibility(View.INVISIBLE);
    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    @OnClick({R2.id.iv_flash,R2.id.tv_finish,R2.id.iv_back,R2.id.iv_last,R2.id.iv_camera_notice,R2.id.iv_small,
                R2.id.iv_big})
    public void onViewClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_flash) {
            if ("off".equals(iv_flash.getTag())) {
                // 打开闪光灯
                iv_flash.setTag("on");
                cv_view.setFlash(Flash.TORCH);
                iv_flash.setImageResource(R.mipmap.x3_iv_flash_open);

            } else {
                // 关闭闪光灯
                iv_flash.setTag("off");
                cv_view.setFlash(Flash.OFF);
                iv_flash.setImageResource(R.mipmap.x3_flash_light_close);
            }
        } else if (id == R.id.tv_finish) {
            if (X3Utils.isFastClick2()) {
                return;
            }
            if (mode == Mode.VIDEO) {
                /**
                 *  完成视频拍摄 开始将多段视频合成一段视频
                 * 如果当前正在有视频拍摄 那么应该现将当前视频拍摄完成 在决定是否合成提交
                 */
                viewProxy.showLoading("");
                iShowTakeOrStop(true);
                if (videoList.size() == 1) {
                    // 回传
                    CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST, videoList);
                    cameraBean.isWork = isWork;
                    EventBus.getDefault().post(cameraBean);
                    if (getActivity() != null) {
                        getActivity().finish();
                        getActivity().overridePendingTransition(0, R.anim.activity_exit);
                    }
                } else {
                    // 需要合成才能返回
                    new Handler().postDelayed(() -> appendAllMovie(), 1000);
                }
            } else {
                if (isAlbum == 3 || isAlbum == 4 || isAlbum == 6) {
                    CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST, cameraList);
                    cameraBean.isWork = isWork;
                    EventBus.getDefault().post(cameraBean);
                    getActivity().finish();
                } else {
                    // 图片模式
                    Intent intent = new Intent(getActivity(), X3CameraCropActivity.class);
                    intent.putExtra("imgHeight", imgHeight);
                    intent.putExtra("itemId", itemId);
                    intent.putExtra("isWork",isWork);
                    intent.putExtra("cameraList", (Serializable) cameraList);
                    startActivity(intent);
                }
            }
        } else if (id == R.id.iv_back) {
            if (videoList.size() > 0) {
                // TODO 已经拍摄视频 中途退出 需要提示
                if (cv_view.isTakingVideo()) {
                    cv_prograss.stopVideo();
                }
                if (exitDialog == null) {
                    exitDialog = new X3PointDialog(getActivity(), "", getString(R.string.x3_no_take_is_exit) + "", getString(R.string.x3_cancel_info) + "", getString(R.string.x3_affirm_info) + "");
                }
                exitDialog.show();
                exitDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                    @Override
                    public void iBtnAffirmClick() {
                        if (getActivity() != null) {
                            getActivity().finish();
                            getActivity().overridePendingTransition(0, R.anim.activity_exit);
                        }
                    }

                    @Override
                    public void iBtnCancelClick() {

                    }
                });

            } else {
                // 没有拍摄视频 直接退出
                if (getActivity() != null) {
                    CameraCloseBean closeBean = new CameraCloseBean(2);
                    EventBus.getDefault().post(closeBean);
                    getActivity().finish();
//                        getActivity().overridePendingTransition(0, R.anim.activity_exit);

                }
            }
        } else if (id == R.id.iv_last) {
            iv_back.setVisibility(View.VISIBLE);
            rl_bottom.setVisibility(View.VISIBLE);
            rl_img.setVisibility(View.GONE);
            cv_view.setVisibility(View.VISIBLE);
            if (isAlbum == 3 || isAlbum == 4 || isAlbum == 6) {
                rl_ai.setVisibility(View.VISIBLE);
            }
            /**
             * 重置预览图片状态
             */
            this.currentPath = "";
            previewAdapter.resetCameraPreview();
            //            case R.id.tv_next:
//                // 回传图片
//                iv_last.setVisibility(View.GONE);
//                tv_next.setVisibility(View.GONE);
//
//                CameraBean cameraBean = new CameraBean(Constent.CODE_CAMERA_REQUEST, cameraList);
//                EventBus.getDefault().post(cameraBean);
//                if (getActivity() != null) {
//                    getActivity().finish();
//                    getActivity().overridePendingTransition(0,R.anim.activity_top_exit);
//                }
//
//                break;
        } else if (id == R.id.iv_camera_notice) {
            if (imageDialog == null) {
                imageDialog = new X3ShowImageDialog(getActivity());
            }
            imageDialog.show();
            imageDialog.showImage(imgUrl);
        } else if (id == R.id.iv_small) {
            int zoom = (int) (cv_view.getZoom() * 100 - 10);
            if (zoom < 0) {
                zoom = 0;
            }
            sb_bar.setProgress(zoom);
            cv_view.setZoom(zoom * 0.01f);
        } else if (id == R.id.iv_big) {
            int zoom = (int) (cv_view.getZoom() * 100 + 10);
            if (zoom > 100) {
                zoom = 100;
            }
            sb_bar.setProgress(zoom);
            cv_view.setZoom(zoom * 0.01f);
        }
    }

    /**
     * 删除最后一项视频
     */
    private void delLastMovie(int position) {
        if (X3StringUtils.isListEmpty(videoList)) {
            return;
        }
        if (position >= timeList.size() || position >= videoList.size()) {
            return;
        }
        /**
         * 删除最后一项视频片段 并且需要删除时间
         */
        float afterTime = takeTime - timeList.get(position);
        cv_prograss.delTime();
        iShowTime(afterTime + "");

        File file = new File(videoList.get(position));
        if (file.exists()) {
            file.delete();
        }
        timeList.remove(position);
        videoList.remove(position);

        if (previewAdapter != null) {
            previewAdapter.delMovie(position);
        }

        tv_finish.setText(getString(R.string.x3_camera_crop_ok));

        if (X3StringUtils.isListEmpty(videoList)) {
            // 没有任何已经拍摄好的视频片段 则隐藏删除按钮
            tv_finish.setVisibility(View.GONE);
            tv_min.setVisibility(View.INVISIBLE);
        }
    }

    private void appendAllMovie() {
        String videoName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        Observable.create((ObservableOnSubscribe<String>) e -> {
            String lastPath = X3FileUtils.getStoragePath(getActivity(), X3FileUtils.MECHANIC_VIDEO_STORAGE_PATH) + "VIDEO_" + videoName + ".mp4";
            X3FileUtils.appendMovie(lastPath,videoList);
            e.onNext(lastPath);
            e.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(path -> {
                    File file = new File(path);
                    if (!file.exists()) {
                        X3ToastUtils.showMessage(getString(R.string.x3_video_create_fail));
                        return;
                    }
                    videoList.clear();
                    videoList.add(path);
                    // 回传
                    CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST,videoList);
                    EventBus.getDefault().post(cameraBean);
                    if (getActivity() != null) {
                        getActivity().finish();
                        getActivity().overridePendingTransition(0, R.anim.activity_exit);
                    }
                });
    }

    @Override
    public void onDestroy() {
        if (viewProxy != null) {
            viewProxy.hideLoading();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (cv_prograss != null) {
            cv_prograss.onDestory();
        }
    }

    @Override
    public void iOnClickVideo() {
        if (!cv_view.isOpened()) {
            return;
        }
        if (cv_view.isTakingVideo()) {
            return;
        }
        ((X3CameraPhotoActivity)getActivity()).hideOrShowTabottom(false);
        // 拍摄视频
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        videoSavePath = X3FileUtils.getStoragePath(getActivity(), X3FileUtils.MECHANIC_VIDEO_STORAGE_PATH) + "VIDEO_" + timeStamp + ".mp4";
        cv_view.takeVideoSnapshot(new File(videoSavePath));

        cv_take.setVisibility(View.INVISIBLE);
        cv_prograss.setVisibility(View.VISIBLE);
        tv_min.setVisibility(View.VISIBLE);
        cv_prograss.lastStartClickTime = System.currentTimeMillis();
        cv_prograss.changePrograss();
        tv_finish.setVisibility(View.GONE);
    }

    @Override
    public void iOnClickPicture() {
        if (!cv_view.isOpened()) {
            return;
        }
        if (isTake) {
            return;
        }
        if (!X3StringUtils.isEmpty(currentPath)) {
            this.currentPath = "";
            isPreviewCamera(false,"");
            return;
        }
        if (cameraList.size() >= allNum) {
            X3ToastUtils.showMessage(String.format(getString(R.string.x3_upload_mast_nine),allNum));
            return;
        }
        // 拍照
        cv_view.takePictureSnapshot();

        /**
         * 当前正在拍摄
         */
        isTake = true;
    }

    @Override
    public void iShowTime(String time) {
        if (getActivity() == null) {
            return;
        }
        if (getActivity().isFinishing()) {
            return;
        }

        this.takeTime = (float) Math.round(Float.parseFloat(time) * 10) / 10;
        if (takeTime < 0 && takeTime > 15) {
            return;
        }
        tv_min.setText(takeTime +"/15.0");
    }

    @Override
    public void iShowEnd() {
        if (getActivity() == null) {
            return;
        }
        if (getActivity().isFinishing()) {
            return;
        }
        if (takeTime == 15) {
            cv_prograss.setOnClickListener(null);
            tv_finish.performClick();
        }
    }

    @Override
    public void iShowTakeOrStop(boolean isStop) {
        if (isStop) {
            // 暂停当前拍摄
            tv_finish.setVisibility(View.VISIBLE);
            if (cv_view.isTakingVideo()) {
                cv_view.stopVideo();
            }
            cv_take.setVisibility(View.VISIBLE);
            cv_take.pictureToVideo();
            if (timeList.size() == 0) {
                timeList.add(this.takeTime);
            }else {
                float allTime = 0;
                for (int i = 0; i < timeList.size(); i++){
                    allTime += timeList.get(i);
                }
                timeList.add(this.takeTime - allTime);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetCameraList(CameraCropBean cropBean) {
        // 传递下方更新标签
        long type = cropBean.type;
        if (type == 1) {
            cameraList = cropBean.cameraList;
            previewAdapter.changeCameraList(cameraList,mode);
            tv_finish.setText(cameraList.size() +"/" + allNum + "\n" + getString(R.string.x3_camera_crop_ok));
            tv_finish.setVisibility(X3StringUtils.isListEmpty(cameraList) ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void iOnCameraPreview(String path,boolean isPreview) {
        this.currentPath = isPreview ? path : "";
        isPreviewCamera(isPreview,path);
    }

    @Override
    public void iOnCameraDelete(String path) {
        if (mode == Mode.PICTURE) {
            if (X3StringUtils.isListEmpty(cameraList)) {
                return;
            }
            if (!X3StringUtils.isEmpty(currentPath)) {
                isPreviewCamera(!path.equals(currentPath),null);
            }
            if (cameraList.contains(path)) {
                cameraList.remove(path);
            }
            tv_finish.setText(cameraList.size() +"/" + allNum + "\n" + getString(R.string.x3_camera_crop_ok));
            tv_finish.setVisibility(X3StringUtils.isListEmpty(cameraList) ? View.GONE : View.VISIBLE);
            return;
        }
        /**
         * 删除视频
         */
        if (X3StringUtils.isListEmpty(videoList)) {
            return;
        }
        if (delDialog == null) {
            delDialog = new X3PointDialog(getActivity(), "", getString(R.string.x3_del_last_video),
                    getString(R.string.x3_cancel_info) + "", getString(R.string.x3_affirm_info));
        }

        delDialog.show();
        delDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
            @Override
            public void iBtnAffirmClick() {
                // 删除对应视频片段
                if (!videoList.contains(path)) {
                    return;
                }
                delLastMovie(videoList.indexOf(path));
            }

            @Override
            public void iBtnCancelClick() {
                if (delDialog != null) {
                    delDialog.dismiss();
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if(mode == Mode.VIDEO){
            MobclickAgent.onPageStart("拍摄页");
        }else {
            MobclickAgent.onPageStart("拍照页");
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if(mode == Mode.VIDEO){
            MobclickAgent.onPageEnd("拍摄页");
        }else {
            MobclickAgent.onPageEnd("拍照页");
        }
    }
}
